/**
 * 添加或者修改页面
 */
var IndentOrderInfoDlg = {
    data: {
        indentOrderNum: "",
        dealer: "",
        purchaseId: "",
        time: "",
        checkCode: "",
        remark: ""
    }
};

layui.use(['form', 'admin', 'ax', 'layedit', 'table', 'tableSelect', 'layer'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var layedit = layui.layedit;
    var lay_table = layui.table;
    var table_select = layui.tableSelect;
    var layer = layui.layer;

    //让当前iframe弹层高度适应
    admin.iframeAuto();

    //表格
    lay_table.render({
        elem: '#purchaseDetail'
        , toolbar: '#toolbar'
        , title: '采购产品表'
        , cellMinWidth: 100
        , totalRow: true
        , data: []
        , cols: [[
            {type: 'numbers', title: '序号', rowspan: 2, fixed: 'left'},
            {field: 'id', title: '产品ID', hide: true, rowspan: 2},
            {field: 'type',hide:true},
            {
                field: 'productName',
                title: '产品名称',
                totalRowText: '合计'
            },{field: 'productModelName', sort: true, title: '产品型号'},
            {field: 'productOrderName', sort: true, title: '产品编号'},
            {field: 'color', sort: true, title: '产品颜色'},
            {field: 'colorNumber', hide: true,sort: true, title: '产品色号'},
            {field: 'material', sort: true,hide: true, title: '产品材质'},
            {field: 'price', sort: true, title: '价格'},
            {field: 'conversionRatio', sort: true,hide:true,title: '换算比率'},
            {field: 'unitName', title: '产品单位', event: 'setUnit', rowspan: 2},
            {field: 'unitId', title: '产品单位id',hide:true},
            {field: 'packageSize', sort: true,hide:true, title: '包装尺寸'},
            {field: 'unitVolume', sort: true, title: '单台体积'},
            {field: 'unitWeight', sort: true, title: '单台净重'},
            {field: 'channel', sort: false,hide: true, title: '渠道'},
            {
                field: 'orderNumbers',
                title: '采购数量',
                rowspan: 2,
                fixed: 'right',
                edit: "number"
            },
            {
                field: 'orderAmount',
                fixed: 'right',
                title: '金额',
                rowspan: 2,
                align: 'center',
                totalRow: true
            },
            {
                field: 'troubleType',
                title: '问题类型',
                rowspan: 2,
                event:'setTrouble'
            },{
                field: 'troubleTypeId',
                rowspan: 2,
                fixed: 'right',
                hide:true
            },
            {
                field: 'afterNum',
                title: '售后数量',
                rowspan: 2,
                fixed: 'right',
                edit: "number"
            },
            {field: 'remark', hide: true},
            {fixed: 'right', align: 'center', title: '操作', rowspan: 2, toolbar: '#tableBar'}
        ]
        ],
        page: false
    });

    //监听单元格编辑
    lay_table.on('edit(productTable)', function (obj) {
        var value = obj.value; //得到修改后的值
        var data = obj.data;
        obj.update({
            type:$("#type").val()
        });
        lay_table.reload('purchaseDetail', {
            data: lay_table.cache['purchaseDetail']
        });
    });
    lay_table.on('tool(productTable)', function (obj) {
        var data = obj.data;

        switch (obj.event) {
            case "del":
                layer.confirm('are you 确定?', function (index) {
                    obj.del();
                    layer.close(index);
                });
                break;
            case "remark":
                layer.prompt({
                    formType: 2,
                    value: data.remark,
                    title: '备注',
                    area: ['500px', '200px'] //自定义文本域宽高
                }, function (value, index, elem) {
                    obj.update({
                        remark: value
                    });

                    layer.close(index);
                });
                break;
            case "setTrouble":
                layer.open({
                    title: "⚙ 选择问题类型",
                    type: 2,
                    skin: 'layui-layer-admin',
                    content: [Feng.ctxPath + '/unit/troubleType'], //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                    area: ['500px', '205px'],
                    end: function (){
                        var trouble = admin.getTempData('ok');
                        console.log(trouble);
                        console.log(trouble.name);
                        console.log(trouble.id);
                        obj.update({
                            troubleType: trouble.name,
                            troubleTypeId: trouble.id
                        });
                        lay_table.reload('purchaseDetail', {
                            data: lay_table.cache['purchaseDetail']
                        });
                    }, cancel: function () {
                        obj.update({
                            unitsId: data.unitsId,
                            orderAmount: getAmount(data.conversionRatio,data.unitId,data.price, data.orderNumbers)
                        });
                        lay_table.reload('purchaseDetail', {
                            data: lay_table.cache['purchaseDetail']
                        });
                    }
                });
                break;
        }
    });

   console.log("传过来的id是："+$("#id").val());

    //头工具栏事件
    lay_table.on('toolbar(productTable)', function (obj) {
        var data = obj.data;
        var checkStatus = lay_table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                top.layui.admin.open({
                    type: 2,
                    area: ["1200px", "650px"],
                    title: '产品添加',
                    content: Feng.ctxPath + '/table_select/sendIndentTableSelect?id='+$("#id").val(),
                    end: function () {
                        var oldData = lay_table.cache['purchaseDetail'];
                        var list = admin.getTempData('product_list');
                        for (var i = 0; i < list.length; i++) {
                            oldData.push(list[i]);
                        }

                        lay_table.reload('purchaseDetail', {
                            data: oldData
                        });
                    }, cancel: function () {
                        admin.putTempData("product_list", null);
                    }
                });
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;
        }
    });








    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {

        var ajax = new $ax(Feng.ctxPath + "/afterIndentOrder/submit", function (data) {
                Feng.success("添加成功!");
            window.location.href = Feng.ctxPath + "/afterIndentOrder";
            //传给上个页面，刷新table用
            admin.putTempData('formOk', true);

            //关掉对话框
            admin.closeThisDialog();
        }, function (data) {
            window.location.href = Feng.ctxPath + "/afterIndentOrder";
            /*Feng.error("添加失败！" + data.responseJSON.message)*/
        });
        var productDetail = lay_table.cache['purchaseDetail'];

        var requestData = [];

        var errorInfo = "";

       /* //数据验证
        productDetail.forEach(function (value, index, array) {
            if (value.orderNumbers === 0) {
                errorInfo += "产品:" + value.productName + "采购数量为0或未填写 ! \n "
            }
            if (value.unitsId === null) {
                errorInfo += "产品:" + value.productName + "单位未填写 ! \n "
            }
        });*/

        if (productDetail.length === 0) {
            Feng.error("请添加产品!");
            return false;
        }

        productDetail.forEach(function (val, index, arr) {
            var afterIndent = {};
            afterIndent.purchaseId = val.id;
            afterIndent.amount = val.afterSaleNum;
            afterIndent.reason = val.remark;
            afterIndent.troubleTypeId = val.troubleTypeId;
            afterIndent.type = val.type;
            requestData.push(afterIndent);
        });
        console.log(JSON.stringify(requestData));
        data.field['afterIndent'] = JSON.stringify(requestData);
        ajax.set(data.field);
        ajax.start();

        return false;

    });

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/afterIndentOrder'
    });

});